package com.qire.manhua.model.viewModel.impl;

import android.view.View;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.model.enumeration.VIPType;
import com.qire.common.support.SmartRefreshViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.MessageCommentDetailController;
import com.qire.manhua.dal.service.MessageCommentDetailService;
import com.qire.manhua.databinding.LayoutMessageCommentReplyItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

/**
 * 消息：评论详情
 */
public class MessageCommentDetailViewModel extends SmartRefreshViewModel<IViewModel> implements IViewModel {

    private MessageCommentDetailService detailService = new MessageCommentDetailService(this);

    private final ArrayList<MessageCommentItemViewModel> messageReplyItemList = new ArrayList<>();

    private final SummerRecyclerBindAdapter messageReplyAdapter = new SummerRecyclerBindAdapter(messageReplyItemList);

    /** 回复的目标评论 */
    private MessageCommentItemViewModel replyToTarget;

    /** 引用参照评论（需要展示详情的评论） */
    private MessageCommentItemViewModel referComment;

    private ComicBookEntity comicBookEntity;

    private int pageNo = 1;

    @Override
    public int getVariableId() {
        return BR.messageCommentDetailViewModel;
    }

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     */
    public void onAddition(MessageCommentDetailController controller) {
        messageReplyAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        this.detailService = null;
        messageReplyAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region    #业务数据 begin

    public void nextPage() {
        this.pageNo++;
    }

    private void resetPage() {
        this.pageNo = 1;
        clearReplyCommentList();
    }

    public int comicBookId() {
        return comicBookEntity.id;
    }

    public void loadDetailData(int commentId) {
        detailService.loadCommentDetail(commentId);
    }

    /**
     * 设置引用参考评论及相关数据
     * @param comicBookEntity 引用评论所属漫画
     * @param referComment 引用参考评论
     */
    public void setReferRelatedData(ComicBookEntity comicBookEntity, MessageCommentItemViewModel referComment) {
        this.comicBookEntity = comicBookEntity;
        this.referComment = referComment;
        refreshReferCommentPanelUI();
        setReplyToTarget(referComment);
        loadReplyData();
    }

    public void loadReplyData() {
        resetPage();
        loadMoreReplyData();
    }

    public void loadMoreReplyData() {
        detailService.loadReplyCommentListData(comicBookId(), referComment.commentId, pageNo);
    }

    public MessageCommentItemViewModel buildCommentItem(int commentId, String userName, String userPortrait, CharSequence commentContent,
                                                        CharSequence commentTime, VIPType vipType, boolean isMyLike, int commentLikeCount, int commentReplyCount) {
        return new MessageCommentItemViewModel(commentId, userName, userPortrait, commentContent,
                commentTime, vipType, isMyLike, commentLikeCount, commentReplyCount);
    }

    public void clearReplyCommentList() {
        messageReplyAdapter.notifyItemRangeRemoved(0, messageReplyItemList.size());
        messageReplyItemList.clear();
    }

    public void addReplyCommentItem(MessageCommentItemViewModel replyCommentItem) {
        messageReplyItemList.add(replyCommentItem);
    }

    public void refreshMessageReplyAdapter() {
        messageReplyAdapter.notifyItemChanged(0, "full");
    }

    public boolean submitReply() {
        if(ObjectUtil.isNull(replyToTarget)) {
            ToastHelper.showToast("请选择想要回复的评论");
            return true;
        }
        String replyContent =  getToValue("replyEditText");
        if(StringUtil.isEmpty(replyContent)) {
            ToastHelper.showToast("发送内容不能为空");
            return false;
        }
        if(replyContent.length() < 10) {
            ToastHelper.showToast("评论不能少于10个字");
            return false;
        }
        if(replyContent.length() > 200) {
            ToastHelper.showToast("请控制字数在200字以内");
            return false;
        }
        detailService.replyComment(comicBookId(), replyToTarget.commentId, replyContent);
        return true;
    }

    //endregion #业务数据 end

    //region    #UI操作 begin

    /**
     * 刷新引用评论的相关信息显示UI
     */
    private void refreshReferCommentPanelUI() {
        set("referComment", referComment);
        set("comicNameText", comicBookEntity.bookName);
        set("repliesCount", referComment.getReplyCount() + "人回复");
    }

    /**
     * 设置指定的回复评论目标
     * @param replyToTarget 指定的回复评论目标
     */
    public void setReplyToTarget(MessageCommentItemViewModel replyToTarget) {
        if(ObjectUtil.nonNull(replyToTarget)) {
            this.replyToTarget = replyToTarget;
            set("replyEditHintText", "回复 " + this.replyToTarget.userName() + ":");
        }
    }

    /**
     * 评论成功后刷新回复后的UI
     */
    public void refreshReplyUI() {
        put("replyEditText", "");
        replyToTarget.addReply();
        if(replyToTarget == referComment) {
            set("repliesCount", referComment.getReplyCount() + "人回复");
        }
    }

    //endregion #UI操作 end

    //region    #UI绑定 begin

    public MutableLiveData<MessageCommentItemViewModel> getReferComment() {
        return get("referComment");
    }

    public MutableLiveData<CharSequence> getComicNameText() {
        return get("comicNameText");
    }

    public MutableLiveData<CharSequence> getRepliesCount() {
        return get("repliesCount");
    }

    public MutableLiveData<String> getReplyEditHintText() {
        return get("replyEditHintText");
    }

    public MutableLiveData<String> getReplyEditText() {
        return get("replyEditText");
    }

    public Adapter getMessageReplyAdapter() {
        return messageReplyAdapter;
    }

    public LayoutManager getMessageLayoutManager() {
        return new LinearLayoutManager(null);
    }

    //endregion #UI绑定 end


    @AdapterEntityBind(viewRid = R.layout.layout_message_comment_reply_item)
    public class MessageCommentItemViewModel extends BaseObservable implements AutoVariable<LayoutMessageCommentReplyItemBinding> {

        private final int commentId;
        private final String userName;
        private final String userPortrait;
        private final CharSequence commentContent;
        private final CharSequence commentTime;
        private final VIPType vipType;
        private boolean isMyLike;
        private int commentLikeCount;
        private int commentReplyCount;

        public MessageCommentItemViewModel(int commentId, String userName, String userPortrait, CharSequence commentContent, CharSequence commentTime,
                                           VIPType vipType, boolean isMyLike, int commentLikeCount, int commentReplyCount) {
            this.commentId = commentId;
            this.userName = userName;
            this.userPortrait = userPortrait;
            this.commentContent = commentContent;
            this.commentTime = commentTime;
            this.vipType = vipType;
            this.isMyLike = isMyLike;
            this.commentLikeCount = commentLikeCount;
            this.commentReplyCount = commentReplyCount;
        }

        @Override
        public void bindVariable(LayoutMessageCommentReplyItemBinding viewBind) {
            viewBind.setMessageCommentItemViewModel(this);
        }

        public boolean isMyLike() {
            return isMyLike;
        }

        public String userName() {
            return userName;
        }

        public String content() {
            return this.commentContent.toString();
        }

        public void addReply() {
            this.commentLikeCount++;
            notifyPropertyChanged(BR.replyCount);
        }

        /**
         * 点赞
         */
        public void giveAlike() {
            if(!isMyLike) {
                isMyLike = true;
                commentLikeCount++;
            }
            detailService.voteToGiveLikeComment(comicBookId(), commentId);
            notifyPropertyChanged(BR.thumbsUpRes);
            notifyPropertyChanged(BR.likeCount);
        }

        /**
         * 举报
         * @param type 举报类型
         * @param content 举报内容
         */
        public void complaint(int type, String content) {
            detailService.complaintComment(comicBookId(), commentId, type, content);
        }

        @Bindable
        public int getPortraitFloatIconVisible() {
            return vipType == VIPType.VIP ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public String getPortraitPath() {
            return userPortrait;
        }

        @Bindable
        public String getUserName() {
            return userName;
        }

        @Bindable
        public String getUserNameColor() {
            return vipType == VIPType.VIP ? "#ff5050" : "#666666";
        }

        @Bindable
        public CharSequence getContent() {
            return commentContent;
        }

        @Bindable
        public CharSequence getCommentTime() {
            return commentTime;
        }

        @Bindable
        public int getThumbsUpRes() {
            return isMyLike ? R.drawable.app_comic_detail_comment_icon_give_like_b : R.drawable.app_comic_detail_comment_icon_give_like_a;
        }

        @Bindable
        public String getLikeCount() {
            return StringUtil.toSymbol(commentLikeCount);
        }

        @Bindable
        public String getReplyCount() {
            return StringUtil.toSymbol(commentReplyCount);
        }

    }


}
